// Copyright (c) 2025, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// ignore_for_file: prefer_expression_function_bodies

import 'dart:io';

import 'package:json_syntax_generator/json_syntax_generator.dart';

import '../test/schema/helpers.dart';

const generateFor = ['hooks', 'code_assets', 'data_assets'];

final rootSchemas = loadSchemas([
  packageUri.resolve('doc/schema/'),
  packageUri.resolve('../code_assets/doc/schema/'),
  packageUri.resolve('../data_assets/doc/schema/'),
]);

void main(List<String> args) {
  for (final packageName in generateFor) {
    const schemaName = 'shared';
    final schemaUri = packageUri.resolve(
      '../$packageName/doc/schema/$schemaName/shared_definitions.schema.json',
    );
    final schema = rootSchemas[schemaUri]!;
    final analyzedSchema =
        SchemaAnalyzer(
          schema,
          nameOverrides: {
            'ios': 'iOS',
            'Ios': 'IOS',
            'macos': 'macOS',
            'Macos': 'MacOS',
            'prefer-dynamic': 'preferDynamicOld',
            'prefer-static': 'preferStaticOld',
            'assetsForLinking': 'assetsForLinkingOld',
            'CodeAssetsCodeAsset': 'NativeCodeAssetNew',
            'DataAssetsDataAsset': 'DataAssetNew',
          },
          publicSetters: [
            'BuildOutput',
            'Config',
            'ConfigExtensions',
            'HookInput',
            'HookOutput',
            'LinkOutput',
          ],
          visbleUnionTagValues: ['Asset'],
        ).analyze();
    final textDumpFile = File.fromUri(
      packageUri.resolve(
        '../native_assets_cli/lib/src/$packageName/syntax.g.txt',
      ),
    );
    if (args.contains('-d')) {
      textDumpFile.writeAsStringSync(analyzedSchema.toString());
    } else if (textDumpFile.existsSync()) {
      textDumpFile.deleteSync();
    }
    final output =
        SyntaxGenerator(
          analyzedSchema,
          header: '''
// This file is generated, do not edit.
// File generated by pkgs/hooks/tool/generate_syntax.dart.
// Must be rerun when pkgs/$packageName/doc/schema/ is modified.
''',
        ).generate();
    final outputUri = packageUri.resolve(
      '../native_assets_cli/lib/src/$packageName/syntax.g.dart',
    );
    File.fromUri(outputUri).writeAsStringSync(output);
    Process.runSync(Platform.executable, ['format', outputUri.toFilePath()]);
    print('Generated $outputUri');
  }
}

Uri packageUri = findPackageRoot('hooks');
